# -*- coding:utf-8 -*-
import json
import Tkinter as tk
import tkMessageBox as MessageBox
import tkFileDialog as filedialog
import ttk
import sys
import os
import xlwt
from collections import OrderedDict
import imageio
import shutil
appdata = os.getenv("LOCALAPPDATA")+'/imageio/ffmpeg'
if not os.path.exists(appdata+'/ffmpeg-win32-v3.2.4.exe'):
	os.makedirs(appdata)
	oldPaths = os.path.dirname(sys.argv[0])+'/ffmpeg-win32-v3.2.4.exe'
	shutil.copy(oldPaths,appdata)
#imageio.plugins.ffmpeg.download()

'''
site_package = 'D:/Python37/site-package'
if not site_package in sys.path:
	sys.path.append(site_package)
'''
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.audio.io.AudioFileClip import AudioFileClip
#from moviepy.editor import *
Count = 0
edl_len = 0
#u’帧数转换,镜头号’
def read_edl(path):
	with open(path,"r") as f:
		edl_list=[]
		for text in f.readlines():
			if 'AX' in text and "V" in text :
				text_time = text.split()
				start = text_time[-2].split(":")
				end = text_time[-1].split(":")
			elif '* FROM CLIP NAME:' in text:
				if ".mp4" not in text:
					text_name = text.split()
					name = text_name[-1]
					edl_dict={"start_frame":start,"end_frame":end,"short":name}
					edl_list.append(edl_dict)
		return edl_list

#u'json文件'
def json_file(edl_path,Video_path):
	video = VideoFileClip(Video_path)
	frames = int(video.fps)
	json_list=[]
	for edl_dict in edl_path:
		short = edl_dict["short"]
		start = edl_dict["start_frame"]
		end = edl_dict["end_frame"]
		start_frame = int(start[-3]) * 60 * frames + int(start[-2]) * frames + int(start[-1])
		end_frame = int(end[-3]) * 60 * frames + int(end[-2]) * frames + int(end[-1])
		frame = end_frame - start_frame+100
		all_frame=end_frame - start_frame
		info_json=OrderedDict()
		info_json["short"]=short
		info_json["start"]=101
		info_json["end"]=frame
		info_json["frame"] = all_frame
		json_list.append(info_json)
		progress_bar()
	return json_list

#u剪切视频,音频,分割镜头号’
def subclip(edl_path,Video_path):
	edl = read_edl(edl_path)
	video = VideoFileClip(Video_path)
	audio = AudioFileClip(Video_path)
	frames = int(video.fps)
	clip_list = []
	for i in edl:
		start = i["start_frame"]
		end = i["end_frame"]
		short = i["short"]
		sp_short=short.split("-")
		start_frame = float(start[-2]) + float(start[-1]) / frames
		end_frame = float(end[-2]) + (float(end[-1]) - 0.5) / frames
		video_clip = video.subclip((float(start[-3]), start_frame), (float(end[-3]), end_frame))
		audio_clip = audio.subclip((float(start[-3]), start_frame), (float(end[-3]), end_frame))
		clip_dict = {"short": sp_short, "video_clip": video_clip,"audio_clip":audio_clip}
		clip_list.append(clip_dict)
	return clip_list
'''
a=subclip("D:/ababab/" + u"最新故事版.edl","D:/ababab/Ep001_story.mp4")
for s in a:
	short_number=s["short"]
	video_clip=s["video_clip"]
	print(short_number)
'''
#u‘视频剪切‘
def clip_video(edl_name, video):
	for c_video in video:
		short_number = c_video["short"]
		short_number1 = []
		if len(short_number) < 4:
			short_number1 = [short_number[0], short_number[1]]
		else:
			short_number1 = [short_number[1], short_number[2]]
		video_path = output_Path.get() + "/mov/str/" + str(edl_name[0:5]) + "-" + short_number1[0]
		if not os.path.exists(video_path):
			os.makedirs(video_path)
		video_clip = c_video["video_clip"]
		video_output = video_clip.write_videofile(video_path + "/ep_"+edl_name[3:5]+"-" + short_number1[0] + "-" + short_number1[1] + "-str.mp4", bitrate='2500k')
		progress_bar()
#u'音频剪切’
def clip_audio(edl_name, audio):
	for c_audio in audio:
		short_number = c_audio["short"]
		short_number1=[]
		if len(short_number)<4:
			short_number1 = [short_number[0],short_number[1]]
		else:
			short_number1 = [short_number[1], short_number[2]]
		audio_path = output_Path.get() + "/prod/sou/" + str(edl_name[0:5]) + "-" + short_number1[0]+ "/" + short_number1[1]
		if not os.path.exists(audio_path):
			os.makedirs(audio_path)
		audio_clip = c_audio["audio_clip"]
		audio_output = audio_clip.write_audiofile(audio_path + "/ep_"+edl_name[3:5]+"-" + short_number1[0] + "-" + short_number1[1] + "-sou.wav", buffersize=2500, bitrate=None)
		progress_bar()
#u'打开窗口弹窗‘
def Edl_path():
	edlPath=filedialog.askopenfilename()
	Edl_Path.set(edlPath)
def Clip_path():
	clipPath=filedialog.askopenfilename()
	Clip_Path.set(clipPath)
def OutPut_Path():
	OutPutPath=filedialog.askdirectory()
	Output_Path.set(OutPutPath)
'''def OutPut_json():
	OutPutJson = filedialog.askdirectory()
	Output_Json.set(OutPutJson)'''
#u"进度条“
'''
def canva():
	for i in range(1, 100):
		progressbar["value"]=i+1
		x.set(str(round(i / 99 * 100, 2)) + '%')
		time.sleep(0.05)
		window.update()
'''
'''
def canva():
	for i in range(Count):
		time.sleep(0.1)
		#5>>>u'坐标',6>>>u'开始进度,25>>>>>u"宽度"
		canvas.coords(fill_rec, (5, 5, 6 + (i / (Count-1)) * 100, 25))
		window.update()
		x.set(str(round(i / (Count-1) * 100, 2)) + '%')
		if round(i / (Count-1) * 100, 2) == 100.00:
			x.set("完成")
'''
def progress_bar():
	global Count
	Count += 1
	index = Count/edl_len*100
	progressbar["value"] = index
	StringVarX.set(str(int(index)) + '%')
	window.update()
def judgeFile(xlsPath):
	try:
		if os.path.isfile(xlsPath):
			os.remove(xlsPath)
	except:
		MessageBox.showerror(u'错误', xlsPath + u'\n表格文件被占用无法删除,请关掉文件,如需保管,请另存为')
		return 0
#u'输出视频,音频‘
def Confirm():
	global edl_len, Count
	Count = 0
	progressbar["value"] = 0
	StringVarX.set(str(0) + '%')

	error_string = ''
	if edlPath.get() == ""and edlPath.get().endswith("edl")==False and os.path.exists(edlPath.get())==False:
		error_string += u'没有edl路径 ,不是edl文件,路径不存在\n'
	if clipPath.get() == "" and clipPath.get().endswith("mp4")==False and os.path.exists(clipPath.get())==False:
		error_string += u'没有视频路径 ,不是mp4文件,路径不存在\n'
	if output_Path.get() == "":
		error_string += u'没有输出路径\n'
	if c1_var.get()==0 and c2_var.get()==0 and c3_var.get()==0:
		error_string += u'没有勾选\n'
	edl_name = os.path.basename(edlPath.get()).split('.')[0]
	if edl_name[0:3]!="ep_" and edl_name[3:5].isdigit()==False:
		print(edl_name,edl_name[3:5])
		error_string += u'不是集数'
	if error_string:
		MessageBox.showerror(u'错误', error_string)
		return
	if judgeFile(output_Path.get()+'/'+edl_name+".xls")==0:
		return
	edl_info = subclip(edlPath.get(), clipPath.get())
	edl_len = len(edl_info)
	if c1_var.get()==1 and c2_var.get()==0 and c3_var.get()==0:
		clip_video(edl_name, edl_info)
	elif c1_var.get()==0 and c2_var.get()==0and c3_var.get()==0:
		clip_audio(edl_name, edl_info)
	elif c1_var.get()==0 and c2_var.get()==0 and c3_var.get()==1:
		file_json(edl_name)
	elif c1_var.get()==1 and c2_var.get()==1 and c3_var.get()==0:
		edl_len*=2
		clip_video(edl_name, edl_info)
		clip_audio(edl_name, edl_info)
	elif c1_var.get()==1 and c2_var.get()==0 and c3_var.get()==1:
		clip_video(edl_name, edl_info)
		file_json(edl_name)
	elif c1_var.get()==0 and c2_var.get()==1 and c3_var.get()==1:
		clip_audio(edl_name, edl_info)
		file_json(edl_name)
	elif c1_var.get()==1 and c2_var.get()==1 and c3_var.get()==1:
		edl_len*=2
		clip_video(edl_name, edl_info)
		clip_audio(edl_name, edl_info)
		file_json(edl_name)
'''
def clear():
	edlPath.delete(0,tk.END)
	clipPath.delete(0,tk.END)
	output_Path.delete(0,tk.END)
	output_video.deselect()
	output_audio.deselect()
'''

'''
for i in range(len(edl[0])):
	print(i)
	start = edl[0][i]
	end = edl[1][i]
	shot = edl[2][i]
'''
#u'输出json'
def file_json(edl_name):
	global edl_len, Count
	Count = 0
	progressbar["value"] = 0
	StringVarX.set(str(0) + '%')
	edl = read_edl(edlPath.get())
	edl_len = len(edl)
	json_info = json_file(edl, clipPath.get())

	with open (output_Path.get()+'/'+edl_name+".json","w") as f:
		json.dump(json_info,f)
	write_Excel(output_Path.get()+'/'+edl_name+".json",edl_name)
def write_Excel(json_info,edl_name):
	with open(json_info,'r')as f:
		jsonInfos = json.load(f)

	workbook = xlwt.Workbook()
	N2 = 0
	tt = 0
	C_sheet = workbook.add_sheet(edl_name, cell_overwrite_ok=True)
	C_sheet.write(0, 0, 'short')
	C_sheet.write(0, 1, 'start')
	C_sheet.write(0, 2, 'end')
	C_sheet.write(0, 3, 'frame')
	for jsonInfo in jsonInfos:
		N2 += 1 + tt
		C_sheet.write(N2, 0, jsonInfo['short'])
		C_sheet.write(N2, 1, jsonInfo['start'])
		C_sheet.write(N2, 2, jsonInfo['end'])
		C_sheet.write(N2, 3, jsonInfo['frame'])
	workbook.save(json_info.replace('.json','.xls'))

#u'窗口'
window = tk.Tk()
window.title("Clip video and audio")
window.geometry("400x300")
window.resizable(0,0)
#u'edl路径‘
edl_path = tk.Label(window,text=u"edl路径:")
edl_path.place(width=65,height=40)
Edl_Path = tk.StringVar()
Edl_Path.set('D:/EP06/ceshi/ep_06_lay.edl')
edlPath = tk.Entry(window,bd=2,textvariable=Edl_Path)
edlPath.place(width=230,height=30,x=62,y=5)
#u'打开文件’
edlPath_Button = tk.Button(window,text="open_edl",command=Edl_path)
edlPath_Button.place(width=90,height=30,x=300,y=5)
#u’要剪切的视频路径‘
clip_path = tk.Label(window,text=u"剪切路径:")
clip_path.place(width=65,height=40,y=45)
Clip_Path=tk.StringVar()
Clip_Path.set('D:/EP06/ceshi/ep_06_lay.mp4')
clipPath=tk.Entry(window,bd=2,textvariable=Clip_Path)
clipPath.place(width=230,height=30,x=62,y=50)
#u'打开文件’
Clip_Button=tk.Button(window,text="open_video",command=Clip_path)
Clip_Button.place(width=90,height=30,x=300,y=47)
#u’输出路径‘
output_path=tk.Label(window,text=u"输出路径：")
output_path.place(width=71,height=40,y=85)
Output_Path=tk.StringVar()
Output_Path.set('D:/EP06/ceshi')
output_Path=tk.Entry(window,bd=2,textvariable=Output_Path)
output_Path.place(width=230,height=30,x=62,y=90)
#u'打开文件夹’
Output_Button=tk.Button(window,text="output_path",command=OutPut_Path)
Output_Button.place(width=90,height=30,x=300,y=90)
#u'输出视频勾选‘  variable>>>>>>u'变量，variable 的值为 1 或 0，代表着选中或不选中'
c1_var=tk.IntVar()
output_video=tk.Checkbutton(window,text=u"输出视频",variable=c1_var,onvalue=1,offvalue=0)
output_video.place(width=71,height=40,y=120,x=10)
#u'输出音频勾选’
c2_var=tk.IntVar()
output_audio=tk.Checkbutton(window,text=u"输出音频",variable=c2_var,onvalue=1,offvalue=0)
output_audio.place(width=71,height=40,y=120,x=100)
#u'输出excel’
c3_var=tk.IntVar()
c3_var.set(1)
output_audio=tk.Checkbutton(window,text=u"输出Excel",variable=c3_var,onvalue=1,offvalue=0)
output_audio.place(width=71,height=40,y=120,x=190)
'''#u'输出json路径‘
output_json=tk.Label(window,text=u'输出json:')
output_json.place(width=71,height=40,y=160,x=-5)
Output_Json=tk.StringVar()
Output_Json.set('D/')
output_Json=tk.Entry(window,bd=2,textvariable=Output_Json)
output_Json.place(width=230,height=30,x=62,y=165)
#u'打开文件夹’
json_Button=tk.Button(window,text="output_json",command=OutPut_json)
json_Button.place(width=90,height=30,x=300,y=165)'''
#u'进度条‘
'''
#创建画布
canvas = tk.Canvas(window,width = 120,height = 30)
canvas.place(x=5,y=170)
x = tk.StringVar()
#u'进度条以及完成程度'
out_rec = canvas.create_rectangle(5,5,105,25,outline = "grey",width = 1)
fill_rec = canvas.create_rectangle(5,5,5,25,outline = "",width = 0,fill = "green")
#u'进度条完成度‘
tk.Label(window,textvariable = x).place(y=175,x=120)
'''
StringVarX = tk.StringVar()
StringVarX.set(str(0) + '%')
progressbar=ttk.Progressbar(window,length=360)
progressbar.place(x=5,y=180)
progressbar["maximum"]=100
progressbar["value"]=0
tk.Label(window,textvariable = StringVarX).place(y=180,x=370)
#u‘输出视频,音频’
confirm=tk.Button(window,text=u"输出文件",command=Confirm)
confirm.place(width=260,height=40,y=240,x=50)
'''#u'输出json
confirm_json=tk.Button(window,text=u"输出json",command=file_json)
confirm_json.place(width=130,height=40,y=240,x=200)'''
'''
cancel=tk.Button(window,text=u'取消',command=clear)
cancel.place(width=150,height=40,y=240,x=200)
'''
window.mainloop()


























